package com.example.source.java.thread;

import java.util.concurrent.atomic.AtomicInteger;

public class PrintThread {
    public static void main(String[] args) {
        AtomicInteger num = new AtomicInteger(1);
        final Object lock = new Object();

        new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    if(num.get() % 2 == 0){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }else {
                        System.out.println(Thread.currentThread().getName() + " " +num.getAndIncrement());
                        lock.notifyAll();
                    }
                    if (num.get() > 100){
                        break;
                    }
                }
            }

        }, "Thread1").start();

        new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    if(num.get() % 2 == 1){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }else {
                        System.out.println(Thread.currentThread().getName() + " " + num.getAndIncrement());
                        lock.notifyAll();
                    }
                    if (num.get() > 100){
                        break;
                    }
                }
            }
        }, "Thread2").start();
    }
}
